package com.tucc.hello.leetcode.no1_400.no1_200.no21_40.no39;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author tucc
 * @description todo
 * @package com.tucc.hello.leetcode
 * @date 2021/5/20
 **/
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] candidates = {2, 3, 5};
        int target = 8;
        List<List<Integer>> result = solution.combinationSum(candidates, target);
        System.out.print(result);
    }

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> total = new ArrayList<>();
        combinationSum(candidates, 0, 0, target, new ArrayList<>(), total);
        return total;
    }

    public void combinationSum(int[] candidates, int cur, int curSum, int target,
                               List<Integer> list, List<List<Integer>> total) {
        if (target == curSum) {
            total.add(new ArrayList<>(list));
        } else {
            for (int i = cur; i < candidates.length; i++) {
                int num = candidates[i];
                if (curSum + num <= target) {
                    list.add(num);
                    combinationSum(candidates, i, curSum + num, target,
                            list, total);
                    list.remove((Integer) num);
                } else {
                    break;
                }
            }
        }
    }

}
